<script setup>
import { shallowRef, computed, reactive, ref, onMounted, inject } from "vue";
import { useWebSocket, useStorage, useScroll } from "@vueuse/core";
import MarkdownIt from "markdown-it";

const smooth = shallowRef(false);
const behavior = computed(() => (smooth.value ? "smooth" : "auto"));
const { y } = useScroll(window, {
    behavior,
});

const item = reactive({
    record: [],
    request: "我想知道机器人在应用方面应该参考什么标准",
    response: "",
    filename: "",
    realtime: false,
    history: false,
});

const alert = inject("alert");
const index = inject("index");
const filename = inject("filename");

const message = ref(undefined);

const md = new MarkdownIt();
const auth = useStorage("auth");

onMounted(() => {
    if (auth.value === undefined) {
        index.value = 2;
        return;
    }

    const { status, data, send, open, close } = useWebSocket(
        "wss://www.isoabc.cn/ws/dialogue/" + auth.value,
        {
            onConnected: function (ws) {
                console.log("websocket 连接成功！", ws);

                const record = useStorage("record").value;
                if (record !== undefined) {
                    item.record = JSON.parse(record);
                    item.history = true;
                }
            },
            onDisconnected: function (ws, event) {
                console.log("onDisconnected");
            },
            onError: function (ws, event) {
                console.log("onError");
            },
            onMessage: function (ws, event) {
                // console.log("event.data", event.data);
                if (event.data) {
                    const info = JSON.parse(event.data);

                    if (info.complete !== true) {
                        item.response += info.msg;
                        item.realtime = true;
                    } else {
                        item.filename = info.filename;

                        item.record.push({
                            request: item.request,
                            response: item.response,
                            filename: item.filename,
                        });

                        useStorage("record").value = JSON.stringify(
                            item.record.slice(-50),
                        );

                        item.realtime = false;
                    }

                    // 这里就是websocket每次发送的消息

                    // 滚动条
                    x();
                }
            },
            // 每隔x毫秒发送一次心跳,heartbeat默认为false
            // heartbeat: true,
            // heartbeat: {
            //   message: 'ping', // 心跳消息
            //   responseMessage: '', // 心跳的响应消息，如果未定义，将使用该消息
            //   interval: 1000, // 间隔(毫秒)
            //   pongTimeout: 1000, // 心跳响应超时，以毫秒为单位,默认为1000
            // },
            /*
             * 不使用心跳，根据后台实际逻辑来，有时候发送心跳，不会返回任何数据，但是不会断开
             * 如果设置为 true，表示需要心跳，发送心跳后，后台一定要返回信息，不然就会断开重连
             * */
            heartbeat: false,
            // autoReconnect: true,
            autoReconnect: {
                retries: 3,
                delay: 2000,
                onFailed() {
                    alert.submit(false, "服务链接失败");
                },
            },
            autoClose: true, // 自动关闭连接
        },
    );

    message.value = send;
});

const submit = () => {
    if (item.request === "") {
        alert.submit(false, "输入问题为空");
        return;
    }

    const data = {
        ping: false,
        content: item.request,
    };

    message.value(JSON.stringify(data));

    item.history = true;
    item.response = "";
    item.filename = "";
};

const x = () => {
    // windowHeight是可视区的高度
    const windowHeight =
        document.documentElement.clientHeight || document.body.clientHeight;
    // scrollHeight是滚动条的总高度
    const scrollHeight =
        document.documentElement.scrollHeight || document.body.scrollHeight;

    const height = scrollHeight - windowHeight;
    console.log(111, y.value, height, scrollHeight, windowHeight);

    if (y.value !== height) {
        y.value = height;
    }
};

const todo = (fn) => {
    index.value = 6;
    filename.value = fn;
};
</script>
<template>
    <div class="flex w-full bottom-10 right-0 z-30">
        <template v-if="item.history !== false">
            <div
                class="w-11/12 mx-auto min-h-screen py-10 flex flex-col text-sm"
                ref="chat"
            >
                <template v-for="(atom, index) in item.record">
                    <p class="my-5">
                        <span
                            class="bg-yellow-400 rounded-r-md rounded-b-md px-5 py-2"
                        >
                            {{ atom.request }}
                        </span>
                    </p>

                    <div>
                        <div class="bg-white rounded-md px-5 py-2">
                            <div
                                class="prose prose-sky text-sm"
                                v-html="md.render(atom.response)"
                            ></div>

                            <div class="flex justify-between text-xs">
                                <p class="flex h-8 leading-8 space-x-4">
                                    <span
                                        @click="todo(atom.filename)"
                                        class="text-blue-600 cursor-pointer"
                                    >
                                        {{ atom.filename }}
                                    </span>
                                </p>

                                <p class="text-gray-500">
                                    以上内容由IS0abc自动生成
                                </p>
                            </div>
                        </div>
                        <template
                            v-if="
                                !item.realtime &&
                                index === item.record.length - 1
                            "
                        >
                            <p class="h-16"></p>
                        </template>
                    </div>
                </template>

                <template v-if="item.realtime">
                    <p class="my-5">
                        <span
                            class="bg-yellow-400 rounded-r-md rounded-b-md px-5 py-2"
                        >
                            {{ item.request }}
                        </span>
                    </p>

                    <div>
                        <div class="bg-white rounded-md px-5 py-2">
                            <div
                                class="prose prose-sky text-sm"
                                v-html="md.render(item.response)"
                            ></div>

                            <div class="flex justify-between text-xs">
                                <p class="flex h-8 leading-8 space-x-4">
                                    <span
                                        @click="todo(item.filename)"
                                        class="text-blue-600 cursor-pointer"
                                    >
                                        {{ item.filename }}
                                    </span>
                                </p>

                                <p class="text-gray-500">
                                    以上内容由IS0abc自动生成
                                </p>
                            </div>
                        </div>
                        <p class="h-16"></p>
                    </div>
                </template>
            </div>
        </template>

        <template v-else>
            <div
                class="w-11/12 mx-auto h-screen py-10 flex flex-col justify-center items-center text-sm overflow-auto"
            >
                <div class="text-iso-gray-300">
                    <p class="h-10 leading-10 flex justify-center items-center">
                        <img class="h-6" src="/logo.png" alt="logo" />
                    </p>
                    <p>查标准、一句话自动生成SOP、产品画册...</p>
                    <p>请把你的任交给我吧~</p>
                </div>
            </div>
        </template>
    </div>

    <div class="fixed flex w-full bottom-10 right-0 z-30">
        <p class="w-48"></p>
        <div class="flex-1">
            <div
                class="w-11/12 mx-auto py-1 bg-white rounded-md border border-gray-200"
            >
                <p class="mx-6 flex justify-between space-x-4">
                    <input
                        type="text"
                        class="h-8 leading-8 w-full rounded-full bg-iso-gray-200 text-sm px-4 outline-0"
                        v-model="item.request"
                        @keydown.enter="submit"
                        placeholder="请输入问题"
                    />
                    <button
                        class="bg-iso-blue-900 rounded-full w-8 h-8 leading-8 text-white flex justify-center items-center"
                        @click="submit"
                    >
                        <svg
                            xmlns="http://www.w3.org/2000/svg"
                            fill="none"
                            viewBox="0 0 24 24"
                            stroke-width="1.5"
                            stroke="currentColor"
                            class="size-5"
                        >
                            <path
                                stroke-linecap="round"
                                stroke-linejoin="round"
                                d="M8.25 6.75 12 3m0 0 3.75 3.75M12 3v18"
                            />
                        </svg>
                    </button>
                </p>
            </div>
        </div>
    </div>
</template>
